package com.stock;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@SpringBootApplication
public class StockApplication implements WebMvcConfigurer {

    @Value("${image.up.path}")
    private String upPath;

    @Value("${image.down.path}")
    private String downPath;

    public static void main(String[] args) {
        SpringApplication.run(StockApplication.class, args);
    }

    @PostConstruct
    public void init() {
        // 创建基础目录
        createDirectoryIfNotExists(upPath);
        createDirectoryIfNotExists(downPath);
        
        System.out.println("图片存储目录初始化完成");
        System.out.println("UP目录: " + new File(upPath).getAbsolutePath());
        System.out.println("DOWN目录: " + new File(downPath).getAbsolutePath());
    }

    private void createDirectoryIfNotExists(String path) {
        File directory = new File(path);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            if (created) {
                System.out.println("Created directory: " + path);
            } else {
                System.out.println("Failed to create directory: " + path);
            }
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 修改资源映射，分别处理up和down目录
        String upAbsolutePath = new File(upPath).getAbsolutePath();
        String downAbsolutePath = new File(downPath).getAbsolutePath();
        
        registry.addResourceHandler("/api/images/up/**")
                .addResourceLocations("file:" + upAbsolutePath + File.separator);
        registry.addResourceHandler("/api/images/down/**")
                .addResourceLocations("file:" + downAbsolutePath + File.separator);
        
        System.out.println("Resource mapping configured:");
        System.out.println("UP path: file:" + upAbsolutePath);
        System.out.println("DOWN path: file:" + downAbsolutePath);
    }
} 